import React, { Component } from 'react';
import { connect } from 'dva';
import { Form, Spin, Modal, Button,Input } from 'antd';
import EditPage from '@/components/EditPage';
import AntdForm from '@/components/AntdForm';
import router from 'umi/router';
import AdSearch from '@/components/AdSearch';
import AdSelect from '@/components/AdSelect';
import AntdFormItem from '@/components/AntdFormItem';
import AntdInput from '@/components/AntdInput';
import AdButton from '@/components/AdButton';

import SearchSelect from '@/components/SearchSelect';
import { formItemFragement, queryDict } from '@/utils/common';
import { allDictList } from '@/utils/constans';
import { allDispatchType, selectDetail, routeUrl, codes, selectICCardList } from './utils';
import Cookie from './Cookie';
import styles from './ICCardList.less'
const { TextArea } = Input;

@connect(({ iccard, component, loading }) => ({
  iccard,
  icCardDetail: iccard.icCardDetail,
  dictObject: component.dictObject,
  formValues: iccard.formValues,
  loading: loading.effects[allDispatchType.detail],
}))
@Form.create()
export default class BillOperate extends Component {
  state = {
    detailId: '',
    type: '',
    visible: false,
    random: '',
  };

  componentWillMount() {
    const allDict = [allDictList.manifest_goods,allDictList.declareListType];
    queryDict({ props: this.props, allDict });
  }

  componentDidMount() {
    const {
      match: {
        params: { id },
      },
    } = this.props;
    if (!id) return;
    this.handleStateChange([{ detailId: id }]);
    this.getBillDetails(id);
  }
  getBillDetails = id => {
    selectDetail({
      type: allDispatchType.detail,
      payload: { id },
      props: this.props,
      callback: data => { },
    });
  };

  handleStateChange = (options = []) => {
    options.map(item => {
      this.setState(item);
    });
  };

  setTabName = payload => {
    const { dispatch } = this.props;
    dispatch({
      type: 'common/setTabsName',
      payload,
      callback: data => {
        if (!data) return;
        router.push(`${routeUrl.edit}/${payload.id}`);
      },
    });
  };

  /**
   * 保存数据
   */
  saveInfo = () => {
    const {
      form,
      match: {
        params: { id },
      },
    } = this.props;
    form.validateFieldsAndScroll((errors, values) => {
      if (errors) return;
      const { ...params } = values;
      if (id) {
        params.id = id;
      }
      this.operateDispatch(params);
    });
  };

  operateDispatch = params => {
    const { dispatch } = this.props;
    dispatch({
      type: allDispatchType.save,
      payload: params,
      callback: data => {
        this.setState(preState => ({
          disabled: !preState.disabled,
        }));
        if (params.id) {
          this.getBillDetails(params.id);
        } else {
          this.setTabName({
            id: data,
            isReplaceTab: true,
          });
        }
        selectICCardList({ props: this.props });
      },
    });
  };

  headerOperate = () => {
    const { disabled, detailId } = this.state;
    return disabled ? (
      <AdButton
        type="primary"
        onClick={() => {
          this.setState(preState => ({
            disabled: !preState.disabled,
          }));
        }}
        text="编辑"
      />
    ) : (
        <Button.Group>
          <AdButton type="primary" onClick={e => this.saveInfo(e)} text="保存" />
          {detailId && (
            <AdButton
              onClick={() => {
                this.setState(preState => ({
                  disabled: !preState.disabled,
                }));
              }}
              text="取消"
            />
          )}
        </Button.Group>
      );
  };
  setCookies = () => {
    this.handleModal('open');
    const { dispatch } = this.props;
    dispatch({
      type: allDispatchType.getRandom,
      payload: {},
      callback: data => {
        this.setState({
          random: data,
        });
      },
    });
  };
  // getCookies = () => {
  //   console.log('document.set-cookie', document['cookie']);
  // };

  handleOK = () => {
    this.child.handleSubmit();
  };
  handleModal = () => {
    this.setState(preState => ({
      visible: !preState.visible,
    }));
  };
  onRef = ref => {
    this.child = ref;
  };

  render() {
    const { detailId, disabled, random } = this.state;
    const { form, icCardDetail, dictObject, loading } = this.props;
    const getFieldDecorator = form.getFieldDecorator;
    const detail = icCardDetail[detailId] || {};

    const editPageParams = {
      title: detail.name || '新增IC卡',
      headerOperate: this.headerOperate(),
      panelTitle: ['基础信息'],
    };
    const commonParams = {
      getFieldDecorator,
    };

    const formItem = [
      // [
      //   detailId && (
      //     <AdButton
      //       text="设置cookie"
      //       type="primary"
      //       code={codes.getCookie}
      //       onClick={() => this.setCookies()}
      //     />
      //   ),
      //   // <AdButton
      //   //   text="获取cookie"
      //   //   type="primary"
      //   //   code={codes.getCookie}
      //   //   onClick={() => this.getCookies()}
      //   // />,
      // ],
      [
        <AntdFormItem
          label="IC卡名称"
          code="name"
          initialValue={detail.name}
          rules={[{ required: true }]}
          {...commonParams}
        >
          <AntdInput disabled={disabled} />
        </AntdFormItem>,
        <AntdFormItem
          label="IC卡cookie信息"
          code="cookie"
          initialValue={detail.cookie}
          rules={[{ required: true }]}
          {...commonParams}
        >
          <AntdInput disabled={disabled} />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="进出境口岸海关代码"
          code="customsCode"
          rules={[{ required: true }]}
          initialValue={detail.customsCode}
          {...commonParams}
        >
          <AntdInput disabled={disabled} />
        </AntdFormItem>,
        <AntdFormItem
          label="卸货地代码"
          code="unloadCode"
          initialValue={detail.unloadCode}
          {...commonParams}
        >
          <AntdInput disabled={disabled} />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="企业代码"
          code="enterpriceCode"
          initialValue={detail.enterpriceCode}
          {...commonParams}
        >
          <AntdInput disabled={disabled} />
        </AntdFormItem>,
        <AntdFormItem
          label="传输企业备案关区"
          code="filingAreaCode"
          initialValue={detail.filingAreaCode}
          {...commonParams}
        >
          <AntdInput disabled={disabled} />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="海关货物通关代码"
          code="goodsItemCode"
          rules={[{ required: true }]}
          initialValue={detail.goodsItemCode || undefined}
          {...commonParams}
        >
          <AdSelect
            disabled={disabled}
            isExist={true}
            data={dictObject[allDictList.manifest_goods]}
          />
        </AntdFormItem>,
        <AntdFormItem
          label="舱单传输人名称"
          code="transprotName"
          initialValue={detail.transprotName}
          {...commonParams}
        >
          <AntdInput disabled={disabled} />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="别名"
          code="alias"
          rules={[{ required: true }]}
          initialValue={detail.alias || undefined}
          {...commonParams}
        >
          <AntdInput
            disabled={disabled}
           
          />
        </AntdFormItem>,
        <AntdFormItem
          label="类型"
          code="type"
          rules={[{ required: true }]}
          initialValue={detail.type}
          {...commonParams}
        >
          <AdSelect
            disabled={disabled}
            isExist={true}
            data={dictObject[allDictList.declareListType]}
          />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="备注"
          code="remarks"
          initialValue={detail.remarks || undefined}
          {...commonParams}
        >
          <TextArea disabled={disabled} rows={4} />
        </AntdFormItem>,
        
      ],
    ];

    return (
      <div className={styles.iccardWarp}>
        <EditPage {...editPageParams}>
          <Spin spinning={detailId ? loading : false}>
            <AntdForm>{formItemFragement(formItem)}</AntdForm>
          </Spin>
        </EditPage>
        <Modal
          title="设置cookies"
          visible={this.state.visible}
          onOk={this.handleOK}
          onCancel={this.handleModal}
          width="400px"
        // footer={false}
        >
          <Cookie onRef={this.onRef} random={random} id={detailId} />
        </Modal>
      </div>
    );
  }
}
